let rewardedVideoAd = null;
// 引入API接口
import * as api from "@/common/lib/api.js";
export const login = {
  created() {

  },
  methods: {
    suanTiem() {
      var getTime = uni.getStorageSync('getTime');
      if (!getTime) {
        return;
      }

      var date = this.getTime(Number(getTime));
      this.userDate = date;
    },
    // 时间戳计算剩余时间
    getTime(time) {
      let date = new Date(time);
      let now = new Date();
      let diff = date.getTime() - now.getTime();
      let day = Math.floor(diff / (24 * 3600 * 1000));
      let hour = Math.floor(diff / (3600 * 1000));
      let min = Math.floor(diff / (60 * 1000));
      let sec = Math.floor(diff / 1000);
      if (day > 0) {
        return day + "天";
      } else if (hour > 0) {
        return hour + "小时";
      } else if (min > 0) {
        return min + "分钟";
      } else if (sec > 0) {
        return sec + "秒";
      } else {
        return "已过期";
      }
    },
    fuzhi() {
      var vipConfig = uni.getStorageSync('vipConfig');
      uni.setClipboardData({
        data: vipConfig.wxText,
        success: function () {
          console.log('success');
        }
      });
    },

    async getVIPList() {
      let detail = await this.$api.getListData({
        dbName: "wx_vip_config"

      });
      let {
        mealList
      } = detail.data[0];
      var user = uni.getStorageSync('user');
      let vipTypes = mealList && mealList.filter((item) => {
        return item.vipType == user.vipType;
      });
      if (vipTypes) {
        if (!vipTypes[0]) {
          this.vipName = '普通用户';
          return;
        }
        this.vipName = vipTypes[0].name;
      }
    },
    qingchc() {
      this.user = {};
      this.uni_id_token = '';
      uni.removeStorageSync('user');
      uni.removeStorageSync('uni_id_token');
    },
    toLogin() {
      uni.navigateTo({
        url: "/pages/my/login/login"
      });

    },
    async getUser(cb) {
      vk.userCenter.getCurrentUserInfo({
        loading: "",
        success: (data) => {
          // 成功后的逻辑
          let userInfo = data.userInfo;
          uni.setStorageSync('user', data.userInfo);
          this.user = userInfo;
          this.user = Object.assign({}, this.user);
          this.uni_id_token = uni.getStorageSync('uni_id_token');
          if (typeof cb == 'function') {
            cb();
          }
        }
      });
    },

    // 登录
    getUserInfo() {
      var that = this;
      // #ifdef MP-WEIXIN
      uni.getUserProfile({
        desc: '个人登录，记录数据', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success(res) {
          console.log(res);
          that.name = res.userInfo.nickName; //昵称
          that.avatar = res.userInfo.avatarUrl; //头像
          that.wxlogin();
        },
        fail() {
          console.log("获取用户信息失败");
        }
      });
      // #endif
      // #ifdef MP-QQ
      uni.getUserInfo({
        // 获取信息成功
        success(res) {
          console.log(res);
          that.name = res.userInfo.nickName; //昵称
          that.avatar = res.userInfo.avatarUrl; //头像
          that.wxlogin();
        },
        fail() {
          console.log("获取用户信息失败");
        }
      });
      // #endif
      // #ifdef  MP-TOUTIAO
      var codeInfo = {};
      tt.login({
        force: true,
        success(res) {
          codeInfo = res;
          console.log(codeInfo);
        },
        fail(res) {
          console.log(`login 调用失败`);
        }
      });
      uni.getUserProfile({
        desc: '个人登录，记录数据', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success(res) {

          that.name = res.userInfo.nickName; //昵称
          that.avatar = res.userInfo.avatarUrl; //头像
          that.wxlogin();
        },
        fail(e) {
          console.log(e);
          console.log("获取用户信息失败");
        }
      });

      // uni.getUserProfile({
      // 	desc: '个人登录，记录数据', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      // 	success(res) {
      // 		console.log("getUserProfile 调用成功：", res.userInfo);
      // 		that.wxlogin();
      // 	},
      // 	fail(res) {
      // 		console.log("getUserProfile 调用失败", res);
      // 	},
      // });
      // #endif

      //  #ifdef APP-PLUS
      uni.getProvider({
        service: 'oauth',
        success: function (res) {
          //支持微信、qq和微博等
          if (~res.provider.indexOf('weixin')) {
            uni.login({
              provider: 'weixin',
              success: function (loginRes) {
                // 获取用户信息
                uni.getUserInfo({
                  provider: 'weixin',
                  success: function (infoRes) {
                    that.name = infoRes.userInfo.
                    nickName; //昵称
                    that.avatar = infoRes.userInfo.
                    avatarUrl; //头像
                    that.openId = loginRes.authResult.openid;
                    uni.showLoading({
                      title: '登录中...'
                    });
                    that.wxloginres();
                  }
                });
              }
            });
          }
        }
      });
      // #endif

    },
    // 初始化用户数据
    async initUserData(data) {
      var mptype;
      // #ifdef MP-WEIXIN
      mptype = 'wx';
      // #endif
      // #ifdef MP-QQ
      mptype = 'qq';
      // #endif
      // #ifdef APP-PLUS
      mptype = 'app_wx';
      // #endif
      // #ifdef H5
      mptype = 'h5_wx';
      // #endif
      // #ifdef MP-TOUTIAO
      mptype = 'toutiao';
      // #endif
      var lifeData = uni.getStorageSync('lifeData');
      var user = uni.getStorageSync('user');
      console.log(data);
      if (data) {
        var param = data;
      } else {
        var param = {
          nickname: '昵称_' + String(new Date().getTime()).slice(10),
          avatar: "/static/default.jpg",
          openid: user.username,
          mp: mptype
        };
      }
      var data = await api.setDataById({
        dbName: "uni-id-users",
        _id: lifeData.$user.userInfo._id,
        dataJson: param
      }, true);
      this.getUser();
    },
    // 微信登陆
    async wxlogin1() {
      let that = this;
      var data1 = {

      };
      vk.userCenter.loginByWeixin({
        data: data1,
        success: async (data) => {
          console.log(data, '1111111111');
          if (data.code == 0) {
            // uni.showToast({
            // 	icon: 'none',
            // 	mask: true,
            // 	title: '登录成功',
            // 	duration: 1500
            // })
            if (data.msg == '注册成功') {
              await this.initUserData(data1);
            }
            that.getUser();
            if (this.hideModal) {
              this.hideModal();
            }
          } else {
            uni.showToast({
              icon: 'none',
              mask: true,
              title: data.msg || '登录失败',
              duration: 1500
            });
          }
        },
        err: (err) => {
          console.log(err);
        }
      });

    },
    //已经授权，自动登录
    async wxlogin() {
      let that = this;
      uni.showLoading({
        title: '登录中...'
      });
      // #ifdef MP-WEIXIN
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          let code = loginRes.code;
          that.wxloginres(code);
        }
      });
      // #endif
      // #ifdef MP-TOUTIAO
      tt.login({
        force: true,
        success(res) {
          console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
          let {
            code,
            anonymousCode
          } = res;
          that.wxloginres(code, anonymousCode);
        },
        fail(res) {
          console.log(`login 调用失败`);
        }
      });
      // #endif

    },
    //登录后提交服务器获取进一步信息
    async wxloginres(wxcode, anonymousCode) {
      let that = this;

      var userId = uni.getStorageSync('userId');

      var mptype;
      // #ifdef MP-WEIXIN
      mptype = 'wx';
      // #endif
      // #ifdef MP-QQ
      mptype = 'qq';
      // #endif
      // #ifdef APP-PLUS
      mptype = 'app_wx';
      // #endif
      // #ifdef H5
      mptype = 'h5_wx';
      // #endif
      // #ifdef MP-TOUTIAO
      mptype = 'toutiao';
      // #endif


      var authorize = await api.user_authorize({
        name: that.name,
        avatar: that.avatar,
        mptype: mptype,
        code: wxcode,
        openid: that.openId,
        anonymousCode: anonymousCode
        // appId: 'tt5f7329cec04d260201',
        // appSecret:"0e8538845b60669ac6cccbdace879246930b552f"
      });
      if (authorize.code == 0) {
        uni.setStorageSync('user', authorize.data);
        // #ifdef MP-TOUTIAO
        let lifeData = uni.getStorageSync('lifeData');
        lifeData.$user.userInfo = authorize.data;
        uni.setStorageSync('lifeData', lifeData);
        let {
          tokenExpired,
          token
        } = authorize.token;
        uni.setStorageSync('uni_id_token', token);
        uni.setStorageSync('uni_id_token_expired', tokenExpired);
        // #endif
        // that.$setInviteUser()
        that.getUser();
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '登录成功',
          duration: 1500
        });

        if (this.suanTiem) {
          this.suanTiem();

        }
        if (this.suanTiem1) {
          this.suanTiem1();

        }
        if (this.hideModal) {
          this.hideModal();
        }
      } else {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: authorize.result.msg,
          duration: 1500
        });
      }
      that.loginShow = false;
    }


  }
};